import request from "@/utils/request";
import {
  type PageDTO,
  type R,
  type ScriptTemplateDTO,
  type ScriptTemplateExecCmd,
  ScriptTemplatePageQry,
  type ScriptTemplateSaveCmd,
  type SseEvent,
  type SseEventReceived
} from "@/types";

function getScriptTemplatePage(qry: ScriptTemplatePageQry): Promise<R<PageDTO<ScriptTemplateDTO>>> {
  return request.get("/api/script-template/page", { params: qry });
}

function getScriptTemplate(id: string): Promise<R<ScriptTemplateDTO>> {
  return request.get("/api/script-template/get-by-id", { params: { id } });
}

function saveScriptTemplate(cmd: ScriptTemplateSaveCmd): Promise<R<string>> {
  return request.post("/api/script-template/save", cmd);
}

function deleteScriptTemplate(id: string): Promise<R<string>> {
  return request.post("/api/script-template/delete", {}, { params: { id } });
}

function execScriptTemplate(cmd: ScriptTemplateExecCmd, received: SseEventReceived): void {
  fetch("/api/script-template/exec", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(cmd)
  }).then((response) => {
    if (response.body === null) {
      throw new Error("Response body is null");
    }
    let buffer = "";

    const reader = response.body.getReader();
    return new ReadableStream({
      start(controller) {
        function push() {
          reader.read().then(({ done, value }) => {
            if (done) {
              controller.close();
              return;
            }
            const text = new TextDecoder("utf-8").decode(value);

            console.log("text=> ", text);

            buffer += text;

            let readLineIndexOf = buffer.indexOf("\n\n");

            while (readLineIndexOf != -1) {
              let firstObjStr = buffer.substring(0, readLineIndexOf);

              console.log("firstObjStr=> ", firstObjStr);

              const lines = firstObjStr.split("\n");

              const event: SseEvent = {
                data: "",
                event: "",
                id: ""
              };

              lines.forEach((line: string) => {
                if (line.indexOf("id:") != -1) {
                  event.id = line.substring(3);
                } else if (line.indexOf("event:") != -1) {
                  event.event = line.substring(6);
                } else if (line.indexOf("data:") != -1) {
                  event.data = line.substring(5);
                }
              });
              received(event);

              buffer = buffer.substring(readLineIndexOf + 1);
              readLineIndexOf = buffer.indexOf("\n\n");

              console.log("buffer", buffer);
            }

            push();
          });
        }

        push();
      }
    });
  });
}

export default {
  getScriptTemplatePage,
  getScriptTemplate,
  saveScriptTemplate,
  deleteScriptTemplate,
  execScriptTemplate
};
